﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MT.Common;
using MT.Common.Helpers;
using MT.Common.Log;
using MT.DAL.Abstract.UserCenter;
using MT.Models.Entity;
using MT.Models.Enumerate;
using MT.WebApi.Core.Auth.OverWrite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MT.Rest.Controllers
{

    [Route("api/[controller]")]
    [Authorize(Roles = "Admin,Client")]
    [ApiController]
    public class AuthApiController : Controller
    {

        /// <summary>
        /// 
        /// </summary>
        public const int DistanceCalue = 500;

        /// <summary>
        /// 
        /// </summary>
        public const int EmbershipNo = 100;

     

        internal User CurrentUser
        {
            get
            {
                var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault();
                var jwt = JwtHelper.SerializeJwt(token);
                // var UserId = MyHttpContext.Current.User.Claims.FirstOrDefault(s => s.Type == "UserId")?.Value.ObjToInt();
                //var ClientTypeDic = HttpContext.User.Claims.FirstOrDefault(s => s.Type == "ClientTypeDic")?.Value;
                //  var uidInHttpcontext = (JwtHelper.SerializeJwt(MyHttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.UserId;
                return new User() { Id = jwt.UserId, ClientTypeDic = jwt.ClientTypeDic };
            }

        }

        protected void ValidationCard(string cardTypeDic, string cardId)
        {
            if (string.IsNullOrEmpty(cardTypeDic) || string.IsNullOrEmpty(cardId)) return;
            if (cardTypeDic == "sfz")
            {
                if (cardId.Length != 18)
                {
                    throw new ApplicationException($"{ ErrorCode.CardIdLengthError.GetEnumDesc()}");
                }
            }
            else
            {
                if (cardId.Length > 50)
                {
                    throw new ApplicationException($"{ ErrorCode.IdentificationNumberError.GetEnumDesc()}");
                }
            }
        }
        protected async Task AddOperateLog(IUserLogService userLogService, ModelTypeEnum modelTypeEnum, OperateTypeEnum operateTypeEnum, List<int> ids, ActiveStateEnum? activeStateEnum)
        {
            await AddOperateLog(userLogService, modelTypeEnum, operateTypeEnum, ids, null, activeStateEnum);
        }

        protected async Task AddOperateLog(IUserLogService userLogService, ModelTypeEnum modelTypeEnum, OperateTypeEnum operateTypeEnum, int id, string operateContent = null)
        {
            await AddOperateLog(userLogService, modelTypeEnum, operateTypeEnum, new List<int>() { id }, operateContent, null);
        }
        protected async Task AddOperateLog(IUserLogService userLogService, ModelTypeEnum modelTypeEnum, OperateTypeEnum operateTypeEnum, List<int> ids, string operateContent = null, ActiveStateEnum? activeStateEnum = null)
        {
            if (activeStateEnum != null)
            {
                operateContent = $"{modelTypeEnum.GetEnumDesc()}/{operateTypeEnum.GetEnumDesc()}/{activeStateEnum.GetEnumDesc()}";
            }
            // 此处需要使用using   因为在多线程情况下 DbContext   Scoped 会被释放,导致异常 using (var context = new AppDbContext())
            await userLogService.CreateUserOperateLogAsync(new UserOperateLog()
            {
                ClientTypeDic = this.CurrentUser.ClientTypeDic,
                CreateTime = DateTime.Now,
                Delete = false,
                InstitutionId = 0,
                Ip = Ip,
                ModelType = (byte)modelTypeEnum,
                UserId = this.CurrentUser.Id,
                Type = (byte)operateTypeEnum,
                OperateContent = string.IsNullOrWhiteSpace(operateContent) ? $"{modelTypeEnum.GetEnumDesc()}/{operateTypeEnum.GetEnumDesc()}" : operateContent,
                OperateIds = ids.Join(",")
            });

        }

     
        /// <summary>
        /// 客户端ip
        /// </summary>
        protected string Ip => HttpContext.Connection.RemoteIpAddress.ToString();
    }
}